﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace MainFrame
{
    public class SerializeHelper
    {
        public static bool isDisplayInfo=true;

        /// <summary>
        /// 信息提示（每个帮助类都加这个，是为了引用单个类和引用多个类时，能共用）
        /// 这种由于有多个判断，会增加时间开销，如果你确定了用哪种显示方式
        /// 且不会再更改，可把本方法注释掉，把下面注释掉的方法启用
        /// </summary>
        /// <param name="chinese">中文提示</param>
        /// <param name="english">英文提示</param>
 


        public static object DeserializeFile<T>(string path,string note)
        {
            try
            {
                if (!File.Exists(path))
                {
                     displalyInfo.displayInfoMain?.Invoke(note + " 参数配置文件不存, parameter file did not exist");
                   
                    return null;
                }
               
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    StreamReader sr = new StreamReader(fs);
                    var str = sr.ReadToEnd();
                    var obj=JsonConvert.DeserializeObject<T>(str);
                     displalyInfo.displayInfoMain?.Invoke(note+" 加载成功, loaded successfully");
                    return obj;
                }


            }
            catch (System.Exception ex)
            {
                 displalyInfo.displayInfoMain?.Invoke(note +$" 加载失败：, load failed：{ex}");
                return null;
            }
        }
   
      

        public static void serializeFile(string path, object obj,string note)
        {
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    string jstr = JsonConvert.SerializeObject(obj);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(jstr);
                    sw.Close();
                }
                 displalyInfo.displayInfoMain?.Invoke(note+ "保存成功，saved successfully");
            }
            catch (System.Exception ex)
            {
                 displalyInfo.displayInfoMain?.Invoke(note +$"保存失败，save failed：{ex}");
            }
        }
    }
}
